package com.gooluke.auth.config;

import com.gooluke.auth.dto.UserDto;
import com.gooluke.auth.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Resource
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {
        UserDto userDto = userService.selectByBasicUserInfo(userId);
        if (userDto == null) {
            throw new UsernameNotFoundException(String.format("No user found with userId '%s'.", userId));
        }
        return new User(userDto.getUsername(), userDto.getPassword(), getAuthorities(userDto.getRoles()));
    }

    private Collection<? extends GrantedAuthority> getAuthorities(List<String> roles) {
        return roles.stream().map(SimpleGrantedAuthority::new).toList();
    }
}